package io.gitee.duxiuhuan.mailbox.service.impl;

import io.gitee.duxiuhuan.mailbox.database.entries.MessageInfo;
import io.gitee.duxiuhuan.mailbox.service.entries.QuestionResult;
import io.gitee.duxiuhuan.mailbox.service.entries.aiRequestResultEntries.Choice;
import io.gitee.duxiuhuan.mailbox.service.entries.aiRequestResultEntries.AIRequestResult;
import io.gitee.duxiuhuan.mailbox.service.inter.MessageManager;
import io.gitee.duxiuhuan.mailbox.service.inter.TalkWithAI;
import io.gitee.duxiuhuan.mailbox.utils.IdUtils;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.stereotype.Service;
import org.springframework.web.servlet.mvc.method.annotation.StreamingResponseBody;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;


@Log4j2
@Service
public class TalkWithAIService implements TalkWithAI {
    
    @Autowired
    private MessageManager messageManager;
    
    @Autowired
    private AIRequestService aiRequestService;
    
    public QuestionResult question(String message, Long userId, Long sessionId, String model, String tableName) {
        try {
            //1. 通过sessionId和userId查询数据库中所有相关对话
            MessageInfo messageInfo = new MessageInfo();
            messageInfo.setSessionId(sessionId);
            messageInfo.setUserId(userId);
            List<MessageInfo> messageInfoList = messageManager.selectMessage("table_" + userId, messageInfo);
            
            //2. 补充当前信息，和查询出来的信息组合起来，一同向目标AI发器请求
            messageInfo.setId(IdUtils.generateId());
            messageInfo.setCreateTime(new Date());
            messageInfo.setContent(message);
            messageInfo.setUserOrSystem(1);
            messageInfo.setModel(model);
            messageInfoList.add(messageInfo);
            
            //3.1 处理AI请求返回结果为MessageInfo，和用户数据信息一起保存进数据库
            List<MessageInfo> messageInfos = new ArrayList<>();
            MessageInfo systemMessageInfo = new MessageInfo();
            systemMessageInfo.setId(IdUtils.generateId());
            systemMessageInfo.setCreateTime(new Date());
            
            //4. 向AI发起请求
            AIRequestResult<Choice> AIRequestResult = aiRequestService.request(model, messageInfoList);
            systemMessageInfo.setContent(AIRequestResult.getChoices().get(0).getMessage().getContent());
            
            //3.2 继续处理
            systemMessageInfo.setUserOrSystem(0);
            systemMessageInfo.setSessionId(messageInfo.getSessionId());
            systemMessageInfo.setModel(model);
            systemMessageInfo.setUserId(userId);
            messageInfos.add(messageInfo);
            messageInfos.add(systemMessageInfo);
            if (!messageManager.insertMessages("table_" + userId, messageInfos)) {
                throw new RuntimeException("更新数据库失败");
            }
            
            //5. 将系统返回信息处理为提问结果类型返回
            QuestionResult questionResult = new QuestionResult();
            questionResult.setData(systemMessageInfo);
            questionResult.setTableName(tableName);
            return questionResult;
        } catch (DataAccessException e) {
            log.error(e.getMessage(), e);
            throw e;
        }
    }
    
    @Override
    public StreamingResponseBody questionStream(String message, Long userId, Long sessionId, String model, String tableName) {
        try {
            MessageInfo messageInfo = new MessageInfo();
            messageInfo.setContent(message);
            //查询请求
            messageInfo.setId(Long.valueOf(IdUtils.generateId()));
            messageInfo.setUserId(userId);
            messageInfo.setCreateTime(new Date());
            messageInfo.setUserOrSystem(1);
            messageInfo.setSessionId(sessionId);
            messageInfo.setModel(model);
            List<MessageInfo> messageInfoList = messageManager.selectMessage("table_" + userId, messageInfo);
            messageInfoList.add(messageInfo);
            
            return aiRequestService.requestStream(model, messageInfoList, userId, tableName);

            
        } catch (DataAccessException e) {
            log.error(e.getMessage(), e);
            throw e;
        }
    }
}
